package com.xddcodec.fs.file.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.xddcodec.fs.file.domain.FileInfo;
import com.xddcodec.fs.file.domain.FileUserFavorites;
import com.xddcodec.fs.file.mapper.FileUserFavoritesMapper;
import com.xddcodec.fs.file.service.FileUserFavoritesService;
import com.xddcodec.fs.framework.common.exception.BusinessException;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xddcodec.fs.file.domain.table.FileInfoTableDef.FILE_INFO;
import static com.xddcodec.fs.file.domain.table.FileUserFavoritesTableDef.FILE_USER_FAVORITES;

/**
 * 用户收藏文件服务实现类
 *
 * @Author: hao.ding@insentek.com
 * @Date: 2025/5/12 13:50
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileUserFavoritesServiceImpl extends ServiceImpl<FileUserFavoritesMapper, FileUserFavorites> implements FileUserFavoritesService {

    private final FileInfoServiceImpl fileInfoService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void favoritesFile(List<String> fileIds) {
        if (CollUtil.isEmpty(fileIds)) {
            throw new BusinessException("收藏文件ID列表不能为空");
        }

        List<String> distinctFileIds = fileIds.stream().distinct().collect(Collectors.toList());
        String userId = StpUtil.getLoginIdAsString();

        // 查询当前用户的文件
        List<FileInfo> fileInfos = fileInfoService.list(
                QueryWrapper.create()
                        .where(FILE_INFO.ID.in(distinctFileIds))
                        .and(FILE_INFO.USER_ID.eq(userId))  // 限制只能收藏自己的文件
                        .and(FILE_INFO.IS_DELETED.eq(false))
        );

        if (fileInfos.isEmpty()) {
            throw new BusinessException("没有找到可收藏的文件或文件不属于您");
        }

        // 查询已收藏的文件
        List<FileUserFavorites> existingFavorites = list(
                new QueryWrapper()
                        .where(FILE_USER_FAVORITES.FILE_ID.in(fileIds))
                        .and(FILE_USER_FAVORITES.USER_ID.eq(userId))
        );
        Set<String> existingFileIds = existingFavorites.stream()
                .map(FileUserFavorites::getFileId)
                .collect(Collectors.toSet());

        // 过滤掉已收藏的文件
        List<FileUserFavorites> favoritesToAdd = fileInfos.stream()
                .filter(fileInfo -> !existingFileIds.contains(fileInfo.getId()))
                .map(fileInfo -> {
                    FileUserFavorites favoritesFile = new FileUserFavorites();
                    favoritesFile.setFileId(fileInfo.getId());
                    favoritesFile.setUserId(userId);
                    return favoritesFile;
                })
                .collect(Collectors.toList());

        if (favoritesToAdd.isEmpty()) {
            log.info("用户 {} 的文件已全部收藏，fileIds: {}", userId, fileIds);
            return;
        }
        this.saveBatch(favoritesToAdd);
    }

    @Override
    public void unFavoritesFile(List<String> fileIds) {
        String userId = StpUtil.getLoginIdAsString();
        this.remove(
                new QueryWrapper()
                        .where(FILE_USER_FAVORITES.FILE_ID.in(fileIds))
                        .and(FILE_USER_FAVORITES.USER_ID.eq(userId))
        );
    }
}
